package com.iussoft.receiveData.service.plugins;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apache.api.manager.PluginConnector;
import com.apache.exception.BusinessException;
import com.apache.tools.StrUtil;
import com.iussoft.analyze.DataReceiveManager;
import com.iussoft.analyze.RequestPactlManager;
import com.iussoft.analyze.impl.SuperDataManager;
import com.iussoft.manager.InterfacePlugin;
import com.iussoft.opc.plugin.OpcUAExtend;
import com.iussoft.receiveData.kafka.KafkaSimpleSender;
import com.iussoft.receiveData.manager.ReceiveManager;
import com.iussoft.receiveData.schedul.ScheduledDynamicTask;
import com.iussoft.tools.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 接口实现父类
 * @author: Hou Dayu
 * @date: Created in 2020/3/13
 */
public abstract class SuperPluginconnector extends SuperDataManager implements PluginConnector {

    @Autowired
    protected ReceiveManager receiveManager;

    @Autowired
    @Qualifier("scheduledDynamicTask")
    protected ScheduledDynamicTask dynamicTask;

    @Autowired(required = false)
    @Qualifier("dataReceiveManager")
    protected DataReceiveManager dataReceiveManager;

    @Autowired
    protected KafkaSimpleSender kafkaSimpleSender;

    protected String sendDataMsg(String traceId, JSONObject resultData, JSONObject interfaceInfo, RequestMessage reqMsg) {
        Long time = System.currentTimeMillis();
        try {
            String result = null;
            String infoCode = interfaceInfo.getString("signConfPlug");
            String decryptClass = null;
            if(StrUtil.isNotNull(infoCode)) {
                String reqMethod = StrUtil.doNull(interfaceInfo.getString("interfaceProtocol"),"");
                Object obj = SpringContextLoader.getBean(infoCode);
                if("opc".equalsIgnoreCase(reqMethod)) {
                    obj = OpcUAExtend.getIntance(unifiedDataDao);//opc插件
                }
                if(obj == null) {
                    obj = this.getSignature(infoCode);
                }
                if (null != obj) {
                    InterfacePlugin plugin = (InterfacePlugin) obj;
                    Map<String, String> params = new HashMap<>();
                    params.put("sourceMsg", reqMsg.getSourceMsg());
                    params.put("signCode", infoCode);
                    params.put("interfaceCode", interfaceInfo.getString("interfaceCode"));
                    params.put("interfaceProtocol", interfaceInfo.getString("interfaceProtocol"));
                    params.put("interfaceUri", interfaceInfo.getString("interfaceUri"));
                    params.put("interfacePort", interfaceInfo.getString("interfacePort"));
                    if("jdbc".equals(reqMethod.toLowerCase())) {
                        params.put("ftpUserName", interfaceInfo.getString("ftpUserName"));
                        params.put("ftpPwd", interfaceInfo.getString("ftpPwd"));
                        params.put("ftpPath", interfaceInfo.getString("ftp_path"));
                    }
                    if(reqMsg.getUrlMap() != null && !reqMsg.getUrlMap().isEmpty()) {
                        params.put("urlParam", JSON.toJSONString(reqMsg.getUrlMap()));
                    }
                    plugin.authentication(params);
                    reqMsg.setSourceMsg(params.get("sourceMsg"));
                    if(StrUtil.isNotNull(params.get("mergeParams"))){
                        resultData.put("mergeParams",params.get("mergeParams"));
                    }
                    if(StrUtil.isNotNull(params.get("defaultColumn"))){//默认列
                        resultData.put("defaultColumn",params.get("defaultColumn"));
                    }
                    result = params.get("responseText");
                    decryptClass = params.get("responseDecrypt");
                }
            }
            if(StrUtil.isNull(result)) {
                RequestPactlManager reqPactManager = null;
                switch (interfaceInfo.getString("interfaceProtocol").toLowerCase()){
                    case "tcp":
                    case "socket":
                        reqPactManager = (RequestPactlManager)SpringContextLoader.getBean("socketPactManager");
                        break;
                    case "ftp":
                        reqPactManager = (RequestPactlManager)SpringContextLoader.getBean("ftpPactManager");
                        break;
                    case "jms":
                        reqPactManager = (RequestPactlManager)SpringContextLoader.getBean("jmsPactManager");
                        break;
                    case "webservice":
                        reqPactManager = (RequestPactlManager)SpringContextLoader.getBean("webservicePacetManager");
                        break;
                    case "jdbc":
                        reqPactManager = (RequestPactlManager)SpringContextLoader.getBean("jDBCPactManager");
                        break;
                    case "http":
                    case "https":
                    default:
                        reqPactManager = (RequestPactlManager)SpringContextLoader.getBean("httpPactManager");
                }
                result = reqPactManager.doInvoke(interfaceInfo,reqMsg,null);
                if(StrUtil.isNotNull(result) && StrUtil.isNotNull(decryptClass)){
                    switch (decryptClass){
                        case "ScriptEngineUtil":
                            result = ScriptEngineUtil.getInstance().decryptCreditCustoms(result);
                            break;
                    }
                }
                if (StrUtil.isNotNull(result) && "xml".equals(interfaceInfo.getString("respMsgFormatType"))) {
                    try {
                        result = JSON.toJSONString(XMLUtil.resolveXmlToMapList(result));
                    } catch (Exception e) {
                    }
                }
            }
            return result;
        } catch (Exception e){
            e.printStackTrace();
            if(e instanceof BusinessException){
                throw e;
            }
        } finally {
            LoggerUtil.infoSource(" tarceId = {}; interfaceCode = {}; message=请求第三方接口耗时; reqCost = {};" ,traceId ,interfaceInfo.getString("interfaceCode"),String.valueOf(System.currentTimeMillis() - time));
        }
        return null;
    }

    protected String getKafkaTopic(int type){
        switch (type){
            case 1:
                return env.getProperty("kafka.receive.topic");
            case 2:
                return env.getProperty("kafka.send.async.topic");
            default:
                return "defaultMessage";
        }
    }

    protected String getConfigByKey(String key){
        return env.getProperty(key);
    }

    protected String rollbackStr(String str){
        StringBuilder resultString = new StringBuilder();
        char[] charArray = str.toCharArray();
        for (int i = charArray.length - 1; i >= 0; i--) {
            resultString.append(charArray[i]);
        }
        return resultString.toString();
    }
}
